<?php

class AdministratorController extends Zend_Controller_Action
{

    /**
    * @var Cms_Model_Administrator
    */
    protected $_administratorModel;

    /**
    * @var array
    */
    protected $_forms = array();

    /**
    * @var Zend_Controller_Action_Helper_Url
    */
    protected $_urlHelper;

    public function init()
    {
        $this->_administratorModel = new Cms_Model_Administrator();

        $this->_urlHelper = $this->_helper->getHelper('url');
    }

    public function groupAction()
    {
        $action = $this->_getParam('do');

            switch($action){

                case 'insert':

                    $this->view->backUrl = $this->_urlHelper->url(array('do'=>'access'),'administratorGroup', true);

                    $this->view->groupForm = $this->_getGroupForm();

                    $request = $this->getRequest();

                     if($request->isPost()){
                          if (!$this->_forms['groupForm']->isValid($request->getPost())) {
                                 return $this->render('savegroup');
                            }

                            $this->_administratorModel->saveAdministratorGroup($this->_forms['groupForm']->getValues());
                            $this->_helper->flashMessenger->setNamespace('returnMessageSuccess')->addMessage("Success: Administrator Group has been successfully created!");
                            $this->_helper->redirector->gotoRoute(array('do'=>'access'),'administratorGroup', true);
                        }

                    $this->_helper->viewRenderer('savegroup');
                    break;

                case 'update':

                    $this->view->backUrl = (null !== $this->_helper->redirectUrl()) ? $this->_helper->redirectUrl() : $this->_urlHelper->url(array('do'=>'access'),'administratorGroup', true);

                    $groupId = (int) $this->_getParam('id');

                    //if group id does not exists - redirect to group access page
                    $groupInfo = $this->_administratorModel->getAdministratorGroupById($groupId);
                    if((null === $groupInfo)){
                        $this->_helper->redirector->gotoRoute(array('do'=>'access'),'administratorGroup', true);
                    }

                    $this->view->groupForm = $this->_getGroupForm('update', $groupId);

                    $request = $this->getRequest();

                    if($request->isPost()){
                          if (!$this->_forms['groupForm']->isValid($request->getPost())) {
                                return $this->render('savegroup');
                            }

                            $this->_administratorModel->saveAdministratorGroup($this->_forms['groupForm']->getValues(), $groupInfo);
                            $this->_helper->flashMessenger->setNamespace('returnMessageSuccess')->addMessage("Success: Administrator Group has been successfully updated!");
                            
                            if(null !== $this->_helper->redirectUrl()){
                                    $this->_redirect($this->_helper->redirectUrl(), array('prependBase'=>false));
                                }else{
                                    $this->_helper->redirector->gotoRoute(array('do'=>'access'),'administratorGroup', true);
                                }
                        }
                        
                    $groupInfo = $groupInfo->toArray();

                    if(isset($groupInfo['accessPermission'])){
                        $groupInfo['accessPermission'] = unserialize($groupInfo['accessPermission']);
                        }
                    if(isset($groupInfo['modifyPermission'])){
                        $groupInfo['modifyPermission'] = unserialize($groupInfo['modifyPermission']);
                        }

                    $this->view->groupForm->populate($groupInfo);

                    $this->_helper->viewRenderer('savegroup');

                    break;
                    
                case 'delete':

                    if($this->getRequest()->isPost()){

                        $groups = $this->_getParam('selected');

                        if ((!empty($groups) && (is_array($groups)))) {
                                $countError = 0;
                                foreach ($groups as $group) {
                                        if($this->_administratorModel->getTotalAdministratorsByGroupId($group) > 0){
                                               $countError += 1;
                                        }else{
                                            $this->_administratorModel->deleteAdministratorGroup(
                                                    $this->_administratorModel->getAdministratorGroupById($group));
                                        }
                                }

                                if($countError > 0){
                                        $this->_helper->flashMessenger->setNamespace('returnMessageWarning')->addMessage("Warning: $countError administrator group(s) cannot be deleted as it is currently assigned to a user(s)!");
                                    }else{
                                        $this->_helper->flashMessenger->setNamespace('returnMessageSuccess')->addMessage("Success: Administrator Group has been successfully deleted!");
                                    }
                        }

                        if(null !== $this->_helper->redirectUrl()){
                                    $this->_redirect($this->_helper->redirectUrl(), array('prependBase'=>false));
                                }else{
                                    $this->_helper->redirector->gotoRoute(array('do'=>'access'),'administratorGroup', true);
                                }
          
                    }else{
                        $this->_helper->redirector->gotoRoute(array('do'=>'access'),'administratorGroup', true);
                        }

                    break;

                case 'access':
                default:

                    if ($this->_helper->flashMessenger->setNamespace('returnMessageSuccess')->hasMessages()) {
                            $this->view->returnMessageSuccess = $this->_helper->flashMessenger->setNamespace('returnMessageSuccess')->getMessages();
                        }

                    if ($this->_helper->flashMessenger->setNamespace('returnMessageWarning')->hasMessages()) {
                            $this->view->returnMessageWarning = $this->_helper->flashMessenger->setNamespace('returnMessageWarning')->getMessages();
                        }

                    $data = array();
                    $partHeadUrl = '';
                    $partPaginationUrl = '';

                    if ($this->_getParam('sort')) {
                            $data['sort'] = $this->_getParam('sort');
                            $partPaginationUrl .= '&sort=' . $this->_getParam('sort');

                            if ($this->_getParam('order')) {
                                $data['order'] = $this->_getParam('order');
                                $partPaginationUrl .= '&order=' . $this->_getParam('order');
                            }else{
                                $data['order'] = 'asc';
                                $partPaginationUrl .= '&order=asc';
                            }
                    }

                    $partHeadUrl .= ($this->_getParam('order') == 'asc') ? '&order=desc' : '&order=asc';

                    if ($this->_getParam('page')){
                            $data['page'] = intval($this->_getParam('page'));
                            $partHeadUrl .= '&page=' . intval($this->_getParam('page'));
                    }else{ //turn on pagination by default
                        $data['page'] = 1;
                    }

                    $this->view->data = $data;
                    $this->view->partHeadUrl = $partHeadUrl;
                    $this->view->partPaginationUrl = $partPaginationUrl;

                    $this->view->groups = ($this->_administratorModel->getAdministratorGroups($data)->count() > 0) ? $this->_administratorModel->getAdministratorGroups($data) : null;
                    $this->_helper->viewRenderer('listgroup');
                    break;
            }


    }

    public function administratorAction()
    {
        $action = $this->_getParam('do');

            switch($action){

                case 'insert':

                    $this->view->backUrl = $this->_urlHelper->url(array('do'=>'access'),'administratorAdministrator', true);

                    $this->view->administratorForm = $this->_getAdministratorForm();

                    $request = $this->getRequest();

                     if($request->isPost()){
                          if (!$this->_forms['administratorForm']->isValid($request->getPost())) {
                                return $this->render('saveadministrator');
                            }

                            $this->_administratorModel->saveAdministrator($this->_forms['administratorForm']->getValues());
                            $this->_helper->flashMessenger->setNamespace('returnMessageSuccess')->addMessage("Success: Administrator has been successfully created!");
                            $this->_helper->redirector->gotoRoute(array('do'=>'access'),'administratorAdministrator', true);
                        }

                    $this->_helper->viewRenderer('saveadministrator');
                    break;

                case 'update':

                    $this->view->backUrl = (null !== $this->_helper->redirectUrl()) ? $this->_helper->redirectUrl() : $this->_urlHelper->url(array('do'=>'access'),'administratorAdministrator', true);

                    $administratorId = (int) $this->_getParam('id');

                    //if administrator id does not exists - redirect to administrator access page
                    $administratorInfo = $this->_administratorModel->getAdministratorById($administratorId);
                    if((null === $administratorInfo)){
                        $this->_helper->redirector->gotoRoute(array('do'=>'access'),'administratorAdministrator', true);
                    }
                    
                    $this->view->administratorForm = $this->_getAdministratorForm('update', $administratorId);

                    $request = $this->getRequest();

                    if($request->isPost()){
                          if (!$this->_forms['administratorForm']->isValid($request->getPost())) {
                                    return $this->render('saveadministrator');
                            }

                            $this->_administratorModel->saveAdministrator($this->_forms['administratorForm']->getValues(), $administratorInfo);
                            $this->_helper->flashMessenger->setNamespace('returnMessageSuccess')->addMessage("Success: Administrator has been successfully updated!");

                            if(null !== $this->_helper->redirectUrl()){
                                    $this->_redirect($this->_helper->redirectUrl(), array('prependBase'=>false));
                                }else{
                                    $this->_helper->redirector->gotoRoute(array('do'=>'access'),'administratorAdministrator', true);
                                }
                        }

                    $this->view->administratorForm->populate($administratorInfo->toArray());

                    $this->_helper->viewRenderer('saveadministrator');

                    break;

                case 'delete':

                    if($this->getRequest()->isPost()){

                        $administrators = $this->_getParam('selected');

                        if ((!empty($administrators) && (is_array($administrators)))) {

                            $authService = new Cms_Service_Authentication();

                                $countError = 0;
                                foreach ($administrators as $administrator) {
                                        if($authService->getIdentity()->adminId == $administrator){
                                               $countError += 1;
                                        }else{
                                            $this->_administratorModel->deleteAdministrator(
                                                    $this->_administratorModel->getAdministratorById($administrator));
                                        }
                                }

                                if($countError > 0){
                                        $this->_helper->flashMessenger->setNamespace('returnMessageWarning')->addMessage("Warning: You can not delete your own account!");
                                    }else{
                                        $this->_helper->flashMessenger->setNamespace('returnMessageSuccess')->addMessage("Success: Administrator(s) has been successfully deleted!");
                                    }
                        }

                        if(null !== $this->_helper->redirectUrl()){
                                    $this->_redirect($this->_helper->redirectUrl(), array('prependBase'=>false));
                                }else{
                                    $this->_helper->redirector->gotoRoute(array('do'=>'access'),'administratorAdministrator', true);
                                }

                    }else{
                        $this->_helper->redirector->gotoRoute(array('do'=>'access'),'administratorAdministrator', true);
                        }

                    break;

                case 'access':
                default:

                    if ($this->_helper->flashMessenger->setNamespace('returnMessageSuccess')->hasMessages()) {
                            $this->view->returnMessageSuccess = $this->_helper->flashMessenger->setNamespace('returnMessageSuccess')->getMessages();
                        }

                    if ($this->_helper->flashMessenger->setNamespace('returnMessageWarning')->hasMessages()) {
                            $this->view->returnMessageWarning = $this->_helper->flashMessenger->setNamespace('returnMessageWarning')->getMessages();
                        }

                    $data = array();
                    $partHeadUrl = '';
                    $partPaginationUrl = '';

                    if ($this->_getParam('sort')) {
                            $data['sort'] = $this->_getParam('sort');
                            $partPaginationUrl .= '&sort=' . $this->_getParam('sort');

                            if ($this->_getParam('order')) {
                                $data['order'] = $this->_getParam('order');
                                $partPaginationUrl .= '&order=' . $this->_getParam('order');
                            }else{
                                $data['order'] = 'asc';
                                $partPaginationUrl .= '&order=asc';
                            }
                    }

                    $partHeadUrl .= ($this->_getParam('order') == 'asc') ? '&order=desc' : '&order=asc';

                    if ($this->_getParam('page')){
                            $data['page'] = intval($this->_getParam('page'));
                            $partHeadUrl .= '&page=' . intval($this->_getParam('page'));
                    }else{ //turn on pagination by default
                        $data['page'] = 1;
                    }

                    $this->view->data = $data;
                    $this->view->partHeadUrl = $partHeadUrl;
                    $this->view->partPaginationUrl = $partPaginationUrl;

                    $this->view->administrators = ($this->_administratorModel->getAdministrators($data)->count() > 0) ? $this->_administratorModel->getAdministrators($data) : null;
                    $this->_helper->viewRenderer('listadministrator');
                    break;
            }


    }

     protected function _getGroupForm($formState='create',$groupId=null)
    {

        $this->_forms['groupForm'] = $this->_administratorModel->getForm('administratorGroupForm');
        $this->_forms['groupForm']->setMethod('post');

        if($formState == 'update'){
            $this->_forms['groupForm']->setAction($this->_urlHelper->url(array('do'=>'update','id'=>$groupId), 'administratorGroup', true).$this->_helper->redirectUrl(true));
        }else{
            $this->_forms['groupForm']->setAction($this->_urlHelper->url(array('do'=>'insert'), 'administratorGroup', true).$this->_helper->redirectUrl(true));
        }

        return $this->_forms['groupForm'];
    }

     protected function _getAdministratorForm($formState='create',$administratorId=null)
    {

        $this->_forms['administratorForm'] = $this->_administratorModel->getForm('administratorAdministratorForm');
        $this->_forms['administratorForm']->setMethod('post');
        
        if($formState == 'update'){
            $this->_forms['administratorForm']->getElement('password')->setRequired(false);
            $this->_forms['administratorForm']->getElement('passwordVerify')->setRequired(false);
            $this->_forms['administratorForm']->setAction($this->_urlHelper->url(array('do'=>'update','id'=>$administratorId), 'administratorAdministrator', true).$this->_helper->redirectUrl(true));
        }else{
            $this->_forms['administratorForm']->removeElement('adminId');
            $this->_forms['administratorForm']->setAction($this->_urlHelper->url(array('do'=>'insert'), 'administratorAdministrator', true).$this->_helper->redirectUrl(true));
        }

        return $this->_forms['administratorForm'];
    }
}